<!-- 新办会员卡 -->
<template>
  <div>
    <el-form :model="dataForm"
             :rules="dataRule"
             ref="dataForm"
             @keyup.enter.native="dataFormSubmit()"
             label-width="108px"
             size="small">
      <el-row>
        <el-col :span="12">
          <el-form-item label="绑定会员资料"
                        prop="memberId">
            <el-tooltip class="item"
                        effect="dark"
                        content="请输入会员的姓名，然后选择罗列出的会员"
                        placement="top">
              <el-select v-model="dataForm.memberId"
                         filterable
                         remote
                         reserve-keyword
                         placeholder="请输入会员姓名"
                         :remote-method="memberMethod"
                         :loading="loading"
                         v-fo
                         clearable
                         @clear="clearMemberHandle"
                         @change="memberChangeHandle"
                         style="width:278px">
                <el-option v-for="item in members"
                           :key="item.id"
                           :label="item.name"
                           :value="item.id"></el-option>
              </el-select>
            </el-tooltip>
          </el-form-item>
        </el-col>
        <el-col :span="12">

        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="会员卡号"
                        prop="cardNumber">
            <!-- show-word-limit -->
            <el-input v-model="dataForm.cardNumber"
                      placeholder="会员卡号"
                      maxlength="8"
                      style="width:278px"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="会员卡类型">
            <el-select v-model="dataForm.cardTypeId"
                       placeholder="请选择会员卡类型"
                       @change="cardTypeChange"
                       style="width:278px">
              <el-option v-for="item in cardtyps"
                         :key="item.id"
                         :label="item.name"
                         :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <!-- <el-col :span="12">
          <el-form-item label="办理方式"
                        prop="method">
            <el-select v-model="dataForm.method"
                       placeholder="请选择办理的方式"
                       style="width:278px">
              <el-option v-for="item in handlemethod"
                         :key="item.id"
                         :value="item.name"></el-option>
            </el-select>
          </el-form-item>
        </el-col> -->

        <el-col :span="12">
          <el-form-item label="可用次数"
                        prop="usage">
            <el-input-number v-model="dataForm.usage"
                             :min="0"
                             label="可用次数"
                             :disabled="usageInputDisabled"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="有效日期"
                        prop="expDate">
            <el-date-picker v-model="dataForm.expDate"
                            type="datetime"
                            placeholder="选择有效日期"
                            style="width:278px"></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <!-- <el-col :span="12">
          <el-form-item label="可用余额"
                        prop="balance">
            <el-input-number v-model="dataForm.balance"
                             :min="0"
                             :max="99999"
                             label="可用余额"
                             :disabled="balanceInputDisabled"></el-input-number>
          </el-form-item>
        </el-col> -->
        <el-col :span="12">
          <el-form-item label="座位号码">
            <el-input v-model="dataForm.seat"
                      placeholder="座位号码"
                      style="width: 278px"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="备注">
            <el-input v-model="dataForm.remark"
                      style="width:278px"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="推荐人">
            <!-- <el-input></el-input> -->
            <el-tooltip class="item"
                        effect="dark"
                        content="推荐人必须先录入基本资料"
                        placement="top">
              <el-select v-model="dataForm.referrerId"
                         filterable
                         remote
                         reserve-keyword
                         placeholder="请输入推荐人姓名"
                         :remote-method="referrerMethod"
                         :loading="loading"
                         clearable
                         style="width:278px"
                         @change="referrerChangeHandle"
                         @clear="clearRefferHandle">
                <el-option v-for="item in referrers"
                           :key="item.id"
                           :label="item.name"
                           :value="item.id"></el-option>
              </el-select>
            </el-tooltip>
          </el-form-item>
        </el-col>
        <el-col :span="12">

        </el-col>
      </el-row>
      <el-row>
        <!-- <el-col :span="12">
          <el-form-item label="可用余额"
                        prop="balance">
            <el-input-number v-model="dataForm.balance"
                             :min="0"
                             :max="99999"
                             label="可用余额"
                             :disabled="balanceInputDisabled"></el-input-number>
          </el-form-item>
        </el-col> -->
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item>
            <el-button v-if="isAuth('member:card:high-add')"
                       type="danger"
                       @click="dataFormSubmit">提交会员卡信息</el-button>
            <el-button v-else-if="isAuth('member:card:save')"
                       type="success"
                       @click="dataFormSubmit">提交会员卡信息</el-button>
            <el-button type="primary"
                       @click="setStepVal(0)">上一步</el-button>
            <!-- <el-button type="primary"
                       @click="setStepVal(2)">下一步</el-button> -->
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';

export default {
  // 接受父组件的值
  props: {
    memberId: Number
  },
  // import引入的组件需要注入到对象中才能使用
  components: {},
  data () {
    // 校验输入的卡号
    var cardNumberValid = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('会员卡号不能为空'))
      }
      let reg = /^\d{1,}$/
      if (reg.test(value)) {
        callback()
      } else {
        callback(new Error('无效会员卡号'))
      }
    }
    // 这里存放数据
    return {
      // 余额和可用次数输入框状态控制
      balanceInputDisabled: false,
      usageInputDisabled: false,

      cardtyps: [], // 会员卡类型数组
      cardtype: '',

      // handlemethod: null,
      // handleValue: '',

      expDate: '',
      members: [],
      referrers: [],
      loading: false,

      dataForm: {
        id: 0,
        memberId: '',
        cardNumber: '',
        cardTypeId: '',
        cardTypeName: '',
        // method: '',
        issueDate: '',
        expDate: '',
        usage: '',
        // balance: '',
        referrerId: '',
        remark: '',
        seat: ''
      },
      dataRule: {
        memberId: [
          { required: true, message: '会员资料编号不能为空', trigger: 'blur' }
        ],
        cardNumber: [
          // { required: true, message: '会员卡号不能为空', trigger: 'blur' }
          { required: true, validator: cardNumberValid, trigger: 'blur' }
        ],
        cardTypeId: [
          { required: true, message: '会员类型编号不能为空', trigger: 'blur' }
        ],
        cardTypeName: [
          { required: true, message: '会员类型名称不能为空', trigger: 'blur' }
        ],
        // method: [
        //   { required: true, message: '办理方式不能为空', trigger: 'blur' }
        // ],
        expDate: [
          { required: true, message: '失效日期不能为空', trigger: 'blur' }
        ],
        usage: [
          { required: true, message: '可用次数不能为空', trigger: 'blur' }
        ]
        // balance: [
        //   { required: true, message: '可用余额不能为空', trigger: 'blur' }
        // ]
      }
    }
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 方法集合
  methods: {
    setStepVal (val) {
      // this.$emit('setStepVal', 0)
      this.$emit('setStepVal', val)
    },

    // 会员卡表单提交
    dataFormSubmit () {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(`/member/card/${!this.dataForm.id ? 'save' : 'update'}`),
            method: 'post',
            data: this.$http.adornData({
              id: this.dataForm.id || undefined,
              memberId: this.dataForm.memberId,
              cardNumber: this.dataForm.cardNumber,
              cardTypeId: this.dataForm.cardTypeId,
              cardTypeName: this.dataForm.cardTypeName,
              // method: this.dataForm.method,
              issueDate: new Date().getTime() / 1000,
              expDate: this.dataForm.expDate.getTime() / 1000,
              usage: this.dataForm.usage,
              // balance: this.dataForm.balance,
              createdBy: this.$store.state.user.name,
              referrerId: this.dataForm.referrerId,
              remark: this.dataForm.remark,
              userId: this.$store.state.user.id
            })
          }).then(({ data }) => {
            // 执行成功判断
            if (data && data.code === 0) {
              // 清空所有字段值
              this.resetFieldsVal()
              // 重置表单
              this.$refs['dataForm'].resetFields()

              // 操作成功提示
              this.$message({
                message: '会员卡新增成功',
                type: 'success',
                duration: 1500
              })

              this.$confirm('是否继续添加会员卡?', '提示', {
                confirmButtonText: '是的',
                cancelButtonText: '不了',
                type: 'warning'
              }).then(() => {
                // 点击是的
              }).catch(() => {
                // 点击不了
                // 设置激活步骤
                this.setStepVal(2)
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      })
    },
    resetFieldsVal () {
      this.balanceInputDisabled = false
      this.usageInputDisabled = false
      // this.cardtyps = []
      this.cardtype = ''
      this.expDate = ''
      this.members = []
      this.referrers = []
      this.loading = false
      for (var item in this.dataForm) {
        this.dataForm[item] = null
      }
    },

    // 查询会员数据
    memberMethod (name) {
      if (!name) {
        return
      }
      this.$http({
        url: this.$http.adornUrl(`/member/member/select/${name}`),
        method: 'get',
        params: this.$http.adornParams()
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.members = data.data
        }
      })
    },

    // 清空会员资料时触发
    clearMemberHandle () {
      this.members = []
      this.dataForm.memberId = ''
    },

    // 当选择的会员发生改变时触发
    memberChangeHandle () {
      // 不允许自己推荐自己
      if (this.dataForm.memberId === this.dataForm.referrerId) {
        this.referrers = []
        this.dataForm.referrerId = ''
      }
    },

    // 获取推荐人数据
    referrerMethod (name) {
      if (!name) {
        return
      }
      this.$http({
        url: this.$http.adornUrl(`/member/member/select/name/${name}`),
        method: 'get',
        params: this.$http.adornParams()
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.referrers = data.data
        }
      })
    },

    // 下拉框发生改变时将调用此函数
    referrerChangeHandle () {
      if (this.dataForm.memberId === this.dataForm.referrerId) {
        this.referrers = []
        this.dataForm.referrerId = ''
      }
    },
    // 推荐人点击清空按钮时触发
    clearRefferHandle () {
      this.dataForm.referrerId = ''
      this.referrers = []
    },

    // 选择的会员卡类型
    cardTypeChange (id) {
      // 会员类型名称
      let cardtype = this.cardtyps.find((item) => {
        return item.id === id
      })

      this.dataForm.cardTypeName = cardtype ? cardtype.name : ''

      // 会员类型对象
      // let cardtype = this.cardtyps.find((item) => {
      //   return item.id === id
      // })
      // console.log(this.$store.state.user)
      // 如果选择的是钻石群主会员
      if (cardtype.code === 'ZSQZHY') {
        // this.usageInputDisabled = true
        // this.balanceInputDisabled = true
        // this.dataForm.usage = 99999
        // this.dataForm.balance = 99999
        this.dataForm.expDate = new Date('2099-12-31 23:59:59')
      } else {
        // this.usageInputDisabled = false
        // this.balanceInputDisabled = false
        // this.dataForm.usage = 0
        // this.dataForm.balance = 0
        this.dataForm.expDate = ''
      }
      this.dataForm.usage = cardtype.defusage
    },

    // 获取会员卡类型
    getCardType () {
      this.$http({
        url: this.$http.adornUrl(`/member/cardtype/list`),
        method: 'get',
        params: this.$http.adornParams()
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.cardtyps = data.page.list
          // console.log(this.cardtyps)
        }
      })
    },
    // 查询办理方式(暂时废除此功能)
    getHandlemethod () {
      this.$http({
        url: this.$http.adornUrl(`/member/handlemethod/list`),
        method: 'get'
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.handlemethod = data.page.list
        }
      })
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created () {
    // this.getHandlemethod()
    this.getCardType()
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted () { },
  beforeCreate () { }, // 生命周期 - 创建之前
  beforeMount () { }, // 生命周期 - 挂载之前
  beforeUpdate () { }, // 生命周期 - 更新之前
  updated () { }, // 生命周期 - 更新之后
  beforeDestroy () { }, // 生命周期 - 销毁之前
  destroyed () { }, // 生命周期 - 销毁完成
  activated () { } // 如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style scoped>
</style>